package main

/*
  @brief 用于演示留言板的模板
  @author lancelot
  @data 2016/12/15
*/

import (
	"encoding/json"
	"errors"
	"gopkg.in/mgo.v2/bson"
	"misakago"
	"time"
)

const (
	MSGBOARD = "msgboard"
)

type MsgBoardModel struct {

	//id编号
	Id_ bson.ObjectId `bson:"_id"`

	//消息
	Msg string `bson:msg`

	Tm int64 `bson:tm`
}

func (model *MsgBoardModel) ToJson() []byte {
	b, err := json.Marshal(*model)
	if err != nil {
		return nil
	}
	return b
}

//压入消息
func MsgBoardPush(handler *misakago.DbHandler, data map[string]interface{}) error {
	var i interface{}
	i, exists := data["msg"]
	if !exists {
		return errors.New("no msg")
	}
	msg := i.(string)

	c := handler.DB.C(MSGBOARD)
	c.Insert(&MsgBoardModel{
		Id_: bson.NewObjectId(),
		Msg: msg,
		Tm:  time.Now().Unix(),
	})
	return nil
}

//弹出超过阈值的消息
func MsgBoardPop(handler *misakago.DbHandler, data map[string]interface{}) error {
	var i interface{}
	i, exists := data["pos"]
	if !exists {
		return errors.New("no pos")
	}
	pos := i.(int)

	c := handler.DB.C(MSGBOARD)

	//查询过量的
	msgs := c.Find(bson.M{}).Sort("-tm").Skip(pos)
	c.RemoveAll(msgs)
	return nil
}

//获取固定阈值的消息
func MsgBoardGet(handler *misakago.DbHandler, data map[string]interface{}) ([]MsgBoardModel, error) {
	var i interface{}
	var msgs []MsgBoardModel

	i, exists := data["limit"]
	if !exists {
		return msgs, errors.New("no limit")
	}
	limit := i.(int)

	c := handler.DB.C(MSGBOARD)

	//查询过量的
	c.Find(bson.M{}).Sort("-tm").Skip(0).Limit(limit).All(&msgs)
	return msgs, nil

}
